package com.dy.yunying.biz.controller.hongbao;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dy.yunying.api.entity.hongbao.HbActivity;
import com.dy.yunying.api.entity.hongbao.HbGiftBag;
import com.dy.yunying.api.entity.hongbao.HbRedpackConfig;
import com.dy.yunying.api.enums.ActivityStatusEnum;
import com.dy.yunying.api.enums.HbRedpackTypeEnum;
import com.dy.yunying.api.resp.hongbao.CashExportVo;
import com.dy.yunying.api.resp.hongbao.RedPackExportVo;
import com.dy.yunying.api.vo.hongbao.HbRedpackConfigVo;
import com.dy.yunying.biz.config.YunYingProperties;
import com.dy.yunying.biz.service.hongbao.ActivityService;
import com.dy.yunying.biz.service.hongbao.HbGiftBagService;
import com.dy.yunying.biz.service.hongbao.HbRedpackConfigService;
import com.google.common.collect.Lists;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import io.swagger.models.auth.In;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 红包配置表
 * @author  chenxiang
 * @version  2021-10-25 14:19:00
 * table: hb_redpack_config
 */
@RestController
@Slf4j
@RequiredArgsConstructor
@RequestMapping("/redpackConfig")
public class HbRedpackConfigController {
	
    private final HbRedpackConfigService hbRedpackConfigService;

	private final ActivityService activityService;

	private final YunYingProperties yunYingProperties;

	private final HbGiftBagService hbGiftBagService;

	/**
	 * 红包列表
	 * @param vo
	 * @return
	 */
	@RequestMapping("/getPage")
	public R getPage(@RequestBody HbRedpackConfigVo vo){
		return hbRedpackConfigService.getPage(vo);
	}
	/**
	 * 添加红包
	 * @param vo
	 * @return
	 */
	@RequestMapping("/addRedPack")
	public R addRedPack(HbRedpackConfigVo vo){
		vo.setId(null);
		try {
			return hbRedpackConfigService.addEditRedPack(vo);
		} catch (Exception e) {
			log.error("保存红包配置信息失败", e);
			return R.failed(e.getMessage());
		}
	}
	/**
	 * 编辑红包
	 * @param vo
	 * @return
	 */
	@RequestMapping("/editRedPack")
	public R editRedPack(HbRedpackConfigVo vo){
		if (StringUtils.isBlank(vo.getId())){
			return R.failed("未获取到主键ID");
		}
		try {
			return hbRedpackConfigService.addEditRedPack(vo);
		} catch (Exception e) {
			log.error("编辑红包配置信息失败", e);
			return R.failed(e.getMessage());
		}

	}
	/**
	 * 红包详情
	 * @param vo
	 * @return
	 */
	@RequestMapping("/details")
	public R details(@RequestBody HbRedpackConfigVo vo){
		if (StringUtils.isBlank(vo.getId())){
			return R.failed("未获取到主键ID");
		}
		return hbRedpackConfigService.details(vo);
	}
	/**
	 * 删除红包
	 * @param vo
	 * @return
	 */
	@RequestMapping("/delRedPack")
	public R delRedPack(@RequestBody HbRedpackConfigVo vo){
		if (StringUtils.isBlank(vo.getId())){
			return R.failed("未获取到主键ID");
		}
		return hbRedpackConfigService.delRedPack(vo);
	}

	/**
	 * 统计活动现金价值
	 * @param vo
	 * @return
	 */
	@RequestMapping("/getCashValues")
	public R getCashValues(@RequestBody HbRedpackConfigVo vo){
		if (StringUtils.isBlank(vo.getActivityId())){
			return R.failed("活动ID不能为空");
		}
		return hbRedpackConfigService.getCashValues(vo);
	}

	@GetMapping("/exportValid")
	public R export4RedPack(@RequestParam Long activityId,@RequestParam Integer type) {
		//校验活动是否下线
		if (yunYingProperties.getRedPackExportStatus()) {
			HbActivity activity = activityService.getById(activityId);
			if (activity == null || !ActivityStatusEnum.CLOSE.getStatus().equals(activity.getActivityStatus())) {
				return R.failed("活动未下线，无需导出");
			}
		}
		if (type.intValue() == 1) {
			List<RedPackExportVo> exportVoList = hbRedpackConfigService.export4RedPack(activityId);
			if (CollectionUtils.isEmpty(exportVoList)) {
				return R.failed("没有未使用的礼包码，无需导出");
			}
		} else if (type.intValue() == 2) {
			List<CashExportVo> exportVoList = hbRedpackConfigService.export4Cash(activityId);
			if (CollectionUtils.isEmpty(exportVoList)) {
				return R.failed("没有未使用的礼包码，无需导出");
			}
		}
		return R.ok();
	}


	@GetMapping("/export4RedPack")
	@PreAuthorize("@pms.hasPermission('EXPORT_GIFT_CODE_BTN_REDPACK')")
	public void export4RedPack(@RequestParam Long activityId, HttpServletResponse response) {
		List<RedPackExportVo> list = Lists.newArrayList();
		try {
			HbActivity activity = activityService.getById(activityId);
			response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			response.setCharacterEncoding("utf-8");
			String fileName = URLEncoder.encode(activity.getActivityName(), "UTF-8").replaceAll("\\+", "%20");
			response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
			response.setHeader("file-name", fileName);
			list = hbRedpackConfigService.export4RedPack(activityId);
			EasyExcel.write(response.getOutputStream(), RedPackExportVo.class)
					.excludeColumnFiledNames(Lists.newArrayList("giftId"))
					.sheet("未使用礼包码一览").doWrite(list);
		} catch (Exception e) {
			log.error("导出红包礼包码失败：{}", e.getMessage());
		} finally {
			//导出完成后将导出内容表示为已删除，避免导入时重复校验
			if (CollectionUtils.isNotEmpty(list)) {
//				List<HbGiftBag> updateList = Lists.newArrayList();
//				list.stream().forEach(item -> {
//					HbGiftBag bag = new HbGiftBag();
//					bag.setId(item.getGiftId());
//					bag.setDeleted(1);
//					bag.setUpdateId(SecurityUtils.getUser().getId().longValue());
//					updateList.add(bag);
//				});
				// deleted 后来被加上了 @TableLogic 注解导致这里更新失效
//				hbGiftBagService.updateBatchById(updateList);
				List<Long> updateList = list.stream().map(RedPackExportVo::getGiftId).collect(Collectors.toList());
				hbGiftBagService.removeByIds(updateList);
				// 活动下线导出礼包码时将未领取完的礼包码总数量更新未已领取数量
				hbRedpackConfigService.updateHasCounts(activityId);
			}
		}
	}

	@GetMapping("/export4Cash")
	@PreAuthorize("@pms.hasPermission('EXPORT_GIFT_CODE_BTN_CASH')")
	public void export4Cash(@RequestParam Long activityId, HttpServletResponse response) {
		List<CashExportVo> list = Lists.newArrayList();
		try {
			HbActivity activity = activityService.getById(activityId);
			response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			response.setCharacterEncoding("utf-8");
			String fileName = URLEncoder.encode(activity.getActivityName(), "UTF-8").replaceAll("\\+", "%20");
			response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
			response.setHeader("file-name", fileName);
			list = hbRedpackConfigService.export4Cash(activityId);
			EasyExcel.write(response.getOutputStream(), CashExportVo.class)
					.excludeColumnFiledNames(Lists.newArrayList("giftId"))
					.sheet("未使用礼包码一览").doWrite(list);
		} catch (Exception e) {
			log.error("导出提现档次礼包码失败：{}", e.getMessage());
		} finally {
			//导出完成后将导出内容表示为已删除，避免导入时重复校验
			if (CollectionUtils.isNotEmpty(list)) {
//				List<HbGiftBag> updateList = Lists.newArrayList();
//				list.stream().forEach(item -> {
//					HbGiftBag bag = new HbGiftBag();
//					bag.setId(item.getGiftId());
//					bag.setDeleted(1);
//					bag.setUpdateId(SecurityUtils.getUser().getId().longValue());
//					updateList.add(bag);
//				});
//				hbGiftBagService.updateBatchById(updateList);
				List<Long> updateList = list.stream().map(CashExportVo::getGiftId).collect(Collectors.toList());
				hbGiftBagService.removeByIds(updateList);
			}
		}
	}
}


